<?php 
class Zen_Behavior_EmailTpl extends Zen_Behavior_Model {
	
	private $_base_path = null;
	
	private $_render = null;
	
	public function __construct($model, $params = array()) {
		parent::__construct($model);
		if (isset($params['render'])) {
			$this->setRender($params['render']);
		}
		if (isset($params['base_path'])) {
			$this->setBasePath($params['base_path']);
		}else{
			$class_name = get_class($model);
			$module_name = preg_replace('/_.*/', '', $class_name) ;
			$this->setBasePath("/site/modules/$module_name/views/");
		}
	}
	
	public function renderHtml($params) {
		if(!$params) return false;
		
		$view = new Zend_View ();
		$view->item = $params;
		$view->setBasePath ( ROOT_PATH . $this->_base_path );
		$text = $view->render ( $this->_render );
		
		return $text;
	}
	
	public function afterCreate($params) {
		
		$html = $this->renderHtml($params);
		$model = $this->getModel();
		$class_name = get_class($model);
		$module_name = preg_replace('/_.*/', '', $class_name) ;
		
		$config = Zen_Settings::get($module_name, 'email');
		$globalConf = Zend_Registry::get ( 'cnf' );
		
		$email = new Communication_Model_Email ();
		if (! isset($config ['email']) || ($config ['email'] == "")) 
			return false;
		$emails = explode ( ',', $config ['email'] );
		
		foreach ( $emails as $rec ) {
			$message = array (
				'from' => $module_name . '@' . $globalConf->domen, 
				'subject' => 'Новое сообщение на сайте ' . $globalConf->domen, 
				'text' => $html, 
				'to' => trim($rec) 
			);
			$email->create ( $message );
		}
		$email->send_messages ();
	}
	
	public function setBasePath($value) {
		$this->_base_path = $value;
		return $this;
	}
	
	public function setRender($value) {
		$this->_render = $value;
		return $this;
	}
	
}